package com.cmc.cloud.cmclink.doc.service.impl.so;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cmc.cloud.cmclink.doc.api.document.emums.*;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.SoVslvoyErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.convert.SoVslvoyConvert;
import com.cmc.cloud.cmclink.doc.entity.SoVslvoyDO;
import com.cmc.cloud.cmclink.doc.mapper.SoVslvoyMapper;
import com.cmc.cloud.cmclink.doc.service.so.SoVslvoyService;
import com.cmc.cloud.cmclink.doc.vo.sovo.sovslvoyvo.*;
import com.cmes.framework.common.exception.util.ServiceExceptionUtil;
import com.cmes.framework.common.pojo.PageResult;
import com.cmes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cmes.framework.security.core.util.SecurityFrameworkUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 订舱航次路径 Service 实现类
 *
 * @author 招商轮船-管理员
 */
@Service
@Validated
public class SoVslvoyServiceImpl implements SoVslvoyService {

    @Resource
    private SoVslvoyMapper soVslvoyMapper;

    @Override
    public void createSoVslvoy(SoVslvoyCreateReqVO createReqVO) {
        // 插入
        SoVslvoyDO soVslvoy = SoVslvoyConvert.INSTANCE.convert(createReqVO);
        soVslvoyMapper.insert(soVslvoy);
    }

    @Override
    public void createOrUpdateAndDeleteBatch(Long soId, List<SoVslvoyUpdateReqVO> newList, List<SoVslvoyRespVO> oldList) {
        createOrUpdateAndDeleteBatch(soId, newList, oldList, true);
    }

    @Override
    public void createOrUpdateAndDeleteBatch(Long soId, List<SoVslvoyUpdateReqVO> newList, List<SoVslvoyRespVO> oldList, boolean insertSpaceApproveStatusNull) {
        // 无效数据直接返回
        if (CollectionUtil.isEmpty(newList) && CollectionUtil.isEmpty(oldList)) {
            return;
        }
        // 默认值
        if (CollectionUtil.isEmpty(newList)) {
            newList = new ArrayList<>();
        }
        if (CollectionUtil.isEmpty(oldList)) {
            oldList = new ArrayList<>();
        }
        List<SoVslvoyUpdateReqVO> createList = new ArrayList<>();
        List<SoVslvoyUpdateReqVO> updateList = new ArrayList<>();
        // 历史数据
        Set<Long> oldIds = oldList.stream().map(e -> e.getId()).collect(Collectors.toSet());
        newList.forEach(e -> {
            if (e.getId() != null) {
                if (oldIds.contains(e.getId())) {
                    // 正常更新
                    updateList.add(e);
                    oldIds.remove(e.getId()); // 剩下的数据需要删除
                } else {
                    // 数据更新非法
                    throw ServiceExceptionUtil.exception(SoVslvoyErrorCodeConstants.SO_VSLVOY_NOT_EXISTS);
                }
            } else {
                e.setSoId(soId);
                //新增默认是空
                if (insertSpaceApproveStatusNull == true) {
                  e.setStatusNull();
                }
                createList.add(e);
            }
        });
        if (CollectionUtil.isNotEmpty(oldIds)) {
            // 没有匹配上的就是前端删除的
            soVslvoyMapper.deleteBatchIds(oldIds);
        }
        if (CollectionUtil.isNotEmpty(createList)) {
            List<SoVslvoyDO> soVslvoyCreateList = SoVslvoyConvert.INSTANCE.convertBatchUpdate(createList);
            soVslvoyMapper.insertBatch(soVslvoyCreateList);
        }
        if (CollectionUtil.isNotEmpty(updateList)) {
            List<SoVslvoyDO> soVslvoyUpdateList = SoVslvoyConvert.INSTANCE.convertBatchUpdate(updateList);
            soVslvoyMapper.updateBatch(soVslvoyUpdateList);
        }
    }

    @Override
    public void createBatch(List<SoVslvoyCreateReqVO> createReqVOList) {
        // 插入
        if (CollectionUtil.isNotEmpty(createReqVOList)) {
            List<SoVslvoyDO> soVslvoyList = SoVslvoyConvert.INSTANCE.convertBatch(createReqVOList);
            soVslvoyMapper.insertBatch(soVslvoyList);
        }
    }

    @Override
    public void updateBatch(List<SoVslvoyUpdateReqVO> updateList) {
        List<SoVslvoyDO> soVslvoyList = SoVslvoyConvert.INSTANCE.convertBatchUpdate(updateList);
        soVslvoyMapper.updateBatch(soVslvoyList);
    }

    @Override
    public void updateBatchDO(List<SoVslvoyDO> updateList) {
        soVslvoyMapper.updateBatch(updateList);
    }

    @Override
    public void updateSoVslvoy(SoVslvoyUpdateReqVO updateReqVO) {
        // 校验存在
        validateSoVslvoyExists(updateReqVO.getId());
        // 更新
        SoVslvoyDO updateObj = SoVslvoyConvert.INSTANCE.convert(updateReqVO);
        soVslvoyMapper.updateById(updateObj);
    }

    @Override
    public void deleteSoVslvoy(Long id) {
        // 校验存在
        validateSoVslvoyExists(id);
        // 删除
        soVslvoyMapper.deleteById(id);
    }
    @Override
    public void deleteSoVslvoyBySoId(Long soId) {
        LambdaUpdateWrapper<SoVslvoyDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SoVslvoyDO::getSoId, soId);
        soVslvoyMapper.delete(updateWrapper);
    }

    private void validateSoVslvoyExists(Long id) {
        if (soVslvoyMapper.selectById(id) == null) {
            throw ServiceExceptionUtil.exception(SoVslvoyErrorCodeConstants.SO_VSLVOY_NOT_EXISTS);
        }
    }

    @Override
    public SoVslvoyDO getSoVslvoy(Long id) {
        return soVslvoyMapper.selectById(id);
    }

    @Override
    public List<SoVslvoyDO> getSoVslvoyList(Collection<Long> ids) {
        return soVslvoyMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<SoVslvoyDO> getSoVslvoyPage(SoVslvoyPageReqVO reqVO) {
        LambdaQueryWrapperX<SoVslvoyDO> queryWrapper = new LambdaQueryWrapperX<>();
        return soVslvoyMapper.selectPage(reqVO, queryWrapper);
    }

    @Override
    public void deleteBySoIds(Collection<Long> sIds) {
        LambdaUpdateWrapper<SoVslvoyDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(SoVslvoyDO::getSoId, sIds);
        soVslvoyMapper.delete(updateWrapper);
    }

    @Override
    public List<SoVslvoyDO> seleteBySoId(Long soId) {
        LambdaQueryWrapper<SoVslvoyDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SoVslvoyDO::getSoId, soId);
        queryWrapper.orderByAsc(SoVslvoyDO::getRouteNo);
        return soVslvoyMapper.selectList(queryWrapper);
    }

    @Override
    public Map<Long, List<SoVslvoyDO>> seleteBySoIdsMap(List<Long> soIds) {
        return seleteBySoIdsMap(soIds, null);
    }

    @Override
    public Map<Long, List<SoVslvoyDO>> seleteBySoIdsMap(List<Long> soIds, String[] spaceStatusList) {
        Map<Long, List<SoVslvoyDO>> resultMap = new HashMap<>(16);
        if (CollectionUtil.isEmpty(soIds)) {
            return resultMap;
        }
        LambdaQueryWrapper<SoVslvoyDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SoVslvoyDO::getSoId, soIds);
        if (spaceStatusList != null && spaceStatusList.length > 0) {
            queryWrapper.in(SoVslvoyDO::getSpaceApproveStatus, Arrays.asList(spaceStatusList));
        }
        queryWrapper.orderByAsc(SoVslvoyDO::getSoId, SoVslvoyDO::getRouteNo);
        List<SoVslvoyDO> list = soVslvoyMapper.selectList(queryWrapper);
        return list.stream().collect(Collectors.groupingBy(SoVslvoyDO::getSoId));
    }

    @Override
    public Map<Long, SoVslvoyDO> selectFirstLinerBySoIdsMap(List<Long> soIds) {
        Map<Long, SoVslvoyDO> resultMap = new HashMap<>(16);
        if (CollectionUtil.isEmpty(soIds)) {
            return resultMap;
        }
        List<SoVslvoyDO> list = soVslvoyMapper.seleceFirstLinerBySoIds(soIds, TransmodeEnum.LINER.getValue());
        return list.stream().collect(Collectors.toMap(SoVslvoyDO::getSoId, e -> e));
    }

    @Override
    public List<SoVslvoyDO> selectFirstLinerBySoIds(List<Long> soIds) {
        if (CollectionUtil.isEmpty(soIds)) {
            throw ServiceExceptionUtil.exception(SoVslvoyErrorCodeConstants.SO_VSLVOY_NOT_EXISTS);
        }
        return soVslvoyMapper.seleceFirstLinerBySoIds(soIds, TransmodeEnum.LINER.getValue());
    }

    @Override
    public void setAllocationIdNull(Collection<Long> ids) {
        LambdaUpdateWrapper<SoVslvoyDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(SoVslvoyDO::getId, ids);
        updateWrapper.set(SoVslvoyDO::getAllocationId, null);
        updateWrapper.set(SoVslvoyDO::getInAutoApproveTrack, false);
        updateWrapper.set(SoVslvoyDO::getAutoApproceProcessFlag, false);
        updateWrapper.set(SoVslvoyDO::getUpdater, String.valueOf(SecurityFrameworkUtils.getLoginUserId()));
        updateWrapper.set(SoVslvoyDO::getUpdateTime, LocalDateTime.now());
        soVslvoyMapper.update(null, updateWrapper);
    }

    @Override
    public void submitDraftSetDefault(List<Long> soIds) {
        LambdaUpdateWrapper<SoVslvoyDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(SoVslvoyDO::getSoId, soIds);
        updateWrapper.eq(SoVslvoyDO::getTransmode, TransmodeEnum.LINER.getValue());
        updateWrapper.set(SoVslvoyDO::getSpaceApproveStatus, ApproveStatusEnum.PENDING.getValue());
        updateWrapper.set(SoVslvoyDO::getUpdater, String.valueOf(SecurityFrameworkUtils.getLoginUserId()));
        updateWrapper.set(SoVslvoyDO::getUpdateTime, LocalDateTime.now());
        soVslvoyMapper.update(null, updateWrapper);

        LambdaUpdateWrapper<SoVslvoyDO> updateWrapperOther = new LambdaUpdateWrapper<>();
        updateWrapperOther.in(SoVslvoyDO::getSoId, soIds);
        //其他方式默认审批通过
        updateWrapperOther.ne(SoVslvoyDO::getTransmode, TransmodeEnum.LINER.getValue());
        updateWrapperOther.set(SoVslvoyDO::getSpaceApproveStatus, ApproveStatusEnum.APPROVED.getValue());
        updateWrapperOther.set(SoVslvoyDO::getUpdater, String.valueOf(SecurityFrameworkUtils.getLoginUserId()));
        updateWrapperOther.set(SoVslvoyDO::getUpdateTime, LocalDateTime.now());
        soVslvoyMapper.update(null, updateWrapperOther);
    }

    @Override
    public List<SoVslvoyApproveSpaceVO> selectByAutoApproveSpace() {
        LocalDate now = LocalDate.now();
        String exImType = ExImTypeEnum.EX.getValue();
        String timeType = BookingTimeTypeEnum.SI_CUT_OFF.getValue();
        String bookingStatus = BookingOpenStatusEnum.OPEN.getValue();
        return soVslvoyMapper.selectByAutoApproveSpace(now, exImType, timeType, bookingStatus);
    }

}
